﻿using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;

namespace 加密算法
{
    public class RSAHelper
    {
        /// <summary>
        /// 生成RSA密钥对
        /// </summary>
        /// <param name="keySize"></param>
        /// <returns></returns>
        public static void GenerateRSAKeyPair(out AsymmetricKeyParameter publicKey, out AsymmetricKeyParameter privateKey)
        {
            var keyGenerationParameters = new KeyGenerationParameters(new SecureRandom(), 2048);
            var generator = new RsaKeyPairGenerator();
            generator.Init(keyGenerationParameters);
            var keyPair = generator.GenerateKeyPair();

            publicKey = keyPair.Public;
            privateKey = keyPair.Private;
        }
        /// <summary>
        /// RSA加密
        /// </summary>
        /// <param name="plaintext"></param>
        /// <param name="publicKey"></param>
        /// <returns></returns>
        public static byte[] EncryptRSA(byte[] dataToEncrypt,byte[] publicKeyBytes)
        {
            var publicKey = PublicKeyFactory.CreateKey(publicKeyBytes);
            var engine = new OaepEncoding(new RsaEngine());
            engine.Init(true, new ParametersWithRandom(publicKey));
            return engine.ProcessBlock(dataToEncrypt, 0, dataToEncrypt.Length);
        }
        /// <summary>
        /// RSA解密
        /// </summary>
        /// <param name="ciphertext"></param>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static byte[] DecryptRSA(byte[] encryptedData,byte[] privateKeyBytes)
        {
            var privateKey = PrivateKeyFactory.CreateKey(privateKeyBytes);
            var engine = new OaepEncoding(new RsaEngine());
            engine.Init(false, privateKey);
            return engine.ProcessBlock(encryptedData, 0, encryptedData.Length);
        }

        /// <summary>
        /// 将公钥转换为字节数组（DER编码）
        /// </summary>
        /// <param name="publicKey"></param>
        /// <returns></returns>
        public static byte[] PublicKeyToBytes(AsymmetricKeyParameter publicKey)
        {
            return SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey).GetDerEncoded();
        }

        /// <summary>
        /// 将私钥转换为字节数组（DER编码）
        /// </summary>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static byte[] PrivateKeyToBytes(AsymmetricKeyParameter privateKey)
        {
            return PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey).GetDerEncoded();
        }
    }
}
